package com.sdkj.fixed.asset.assets.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.assets.in_vo.TransferDetail;
import com.sdkj.fixed.asset.api.assets.in_vo.TransferParam;
import com.sdkj.fixed.asset.api.assets.in_vo.TransferSearchParam;
import com.sdkj.fixed.asset.api.assets.out_vo.TransferResult;
import com.sdkj.fixed.asset.api.assets.out_vo.WarehouseHistoryResult;
import com.sdkj.fixed.asset.api.assets.out_vo.WarehouseResult;
import com.sdkj.fixed.asset.api.login.out_vo.CompanyBaseListResult;
import com.sdkj.fixed.asset.api.login.pojo.LoginUser;
import com.sdkj.fixed.asset.assets.mapper.*;
import com.sdkj.fixed.asset.assets.util.*;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.utils.JpushClientUtil;
import com.sdkj.fixed.asset.pojo.assets.*;
import com.sdkj.fixed.asset.pojo.system.OrgManagement;
import com.sdkj.fixed.asset.pojo.system.PushManagement;
import com.sdkj.fixed.asset.pojo.system.UserManagement;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Author zhangjinfei
 * @Description //TODO 资产调拨
 * @Date 2020/7/21 10:54
 */
@Service
public class TransferService extends BaseService<Transfer> {


    private  final Logger log = LoggerFactory.getLogger(CollectService.class);
    private final static String TABLE_NAME="as_asset_transfer";
    private final static String COLUMN_NAME="transfer_id";
    @Resource
    private TransferMapper mapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private AssetTransferMapper assetTransferMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private CacheUtils cacheUtils;
    @Autowired
    private AssetLogMapper assetLogMapper;
    @Autowired
    private SetAreaMapper areaMapper;
    @Autowired
    private WarehouseHistoryMapper historyMapper;
    @Autowired
    private AssetReportService assetReportService;
    @Autowired
    private PushManagementMapper pushMapper;

    @Override
    public BaseMapper getMapper() {
        return mapper;
    }

    public List<TransferResult> queryPages(PageParams<TransferSearchParam> params){

        //--------- 权限 start
        String token = request.getHeader("token");
        // redis 查询用户权限： 如果是管理员为false 查询全部
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        List<CompanyBaseListResult> companys = loginUser.getCompanys();
        String orgId = companys.get(0).getCompanyId();
        TransferSearchParam param = params.getParams();
        PageHelper.startPage(params.getCurrentPage(),params.getPerPageTotal());
        List<TransferResult> list = mapper.queryPages(param.getSearchName(),param.getState(),orgId,userId);
        list.stream().forEach(e->{
            String transferId = e.getTransferId();
            List<WarehouseHistoryResult> warehouseList = historyMapper.queryWarehouseTransfer(transferId,4);
            e.setWarehouseList(warehouseList);
        });
        return list;
    }
    /**
     * 主键ID 查询 结果集
     * @param transferId
     * @return
     */
    public TransferResult queryTransfer(String transferId) {
        TransferResult result = mapper.selectByTransferId(transferId);
        List<WarehouseHistoryResult> warehouseList = historyMapper.queryWarehouseTransfer(transferId,4);
        result.setWarehouseList(warehouseList);
        return result;
    }

    public Integer insertTransfer(TransferParam transfer) {
        String token = request.getHeader("token");
        LoginUser user = cacheUtils.getUser(token);
        String userId = user.getUserId();
        String userName = user.getUserName();
        String orgId = request.getHeader("orgId");
        Long dbno = redisUtil.getIncr("DB_"+orgId+"_"+DateTools.nowDayStr(), DateTools.expiresTime());
        String strNo = String.format("%04d",dbno);
        String orderNo = "DB"+DateTools.nowDayStr()+strNo;
        transfer.setOrgId(orgId);
        transfer.setTransferOrderNo(orderNo);
        transfer.setTransferOutAdmin(userId);
        transfer.setTransferOutAdminName(userName);
        transfer.setTransferOutTime(DateTools.nowDay());
        transfer.setCreateTime(DateTools.nowDate());
        transfer.setCreateUser(userId);
        transfer.setUpdateTime(DateTools.nowDate());
        transfer.setUpdateUser(userId);
        transfer.setTransferState("0");
        transfer.setIsDelete(0);
        int i = mapper.insertSelective(transfer);
        List<String> assetIdList = transfer.getDetailList().stream()
                .map(e->e.getAssetId()).collect(Collectors.toList());
        assetIdList.stream().forEach(assetId->{
            AssetTransfer assetTransfer = new AssetTransfer();
            assetTransfer.setAssetId(assetId);
            try {
                Warehouse warehouse = warehouseService.selectByPrimaryKey(assetId);
                if(StringUtils.equals("闲置",warehouse.getState())){
                    assetTransfer.setReserved("1");
                }else{
                    assetTransfer.setReserved("2");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            assetTransfer.setTransferId(transfer.getTransferId());
            assetTransfer.setState(0);
            assetTransfer.setCreateDate(DateTools.nowDate());
            assetTransfer.setCreateUser(userId);
            assetTransfer.setUpdateDate(DateTools.nowDate());
            assetTransfer.setUpdateUser(userId);
            assetTransfer.setIsDeleted(0);
            assetTransferMapper.insertSelective(assetTransfer);
        });
        warehouseService.updateAssetState(assetIdList, "调拨中",null,null);
        historyMapper.batchInsert( assetIdList ,transfer.getTransferId(),4);
        insertLog1(transfer);

        //推送消息给领用人
        String[] asia = {transfer.getTransferInAdmin()};
        String notification_title = "资产调拨发起";
        String msg_title = "资产调拨发起";
        String msg_content = "资产调拨发起，单号【"+ transfer.getTransferOrderNo() +"】";
        log.info("资产调拨发起,消息推送人："+ JSONObject.toJSONString(asia));
        JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");
        String finalMsg_content = msg_content;
        Arrays.stream(asia).forEach(e->{
            PushManagement pu = new PushManagement();
            pu.setCompanyId(orgId);
            pu.setContent(finalMsg_content);
            pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            pu.setCuser(userId);
            pu.setSender(e);
            pu.setResult(0);
            pushMapper.insertSelective(pu);
        });

        return i;
    }
    // 添加日志
    private void insertLog1(TransferParam transfer) {
        //--------- 权限 start
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();
        List<TransferDetail> detailList = transfer.getDetailList();
        for (TransferDetail detail:detailList) {
            AssetLog assetLog = new AssetLog();
            assetLog.setCreateTime(DateTools.nowDate());
            assetLog.setCreateUser(userId);
            assetLog.setUpdateTime(DateTools.nowDate());
            assetLog.setUpdateUser(userId);
            assetLog.setLogType("资产调拨");
            assetLog.setAssetId(detail.getAssetId());
            assetLog.setHandlerUser(transfer.getTransferOutAdminName());
            assetLog.setHandlerId(transfer.getTransferId());
            OrgManagement orgOut = warehouseMapper.queryOrgById(transfer.getTransferOutCompany());
            OrgManagement orgIn = warehouseMapper.queryOrgById(transfer.getTransferInCompany());
           String text = "管理员["+userName+"]发起调拨，将资产从["+orgOut.getName()+"]公司,调入["+
                   orgIn.getName()+"]公司";
            assetLog.setHandlerContext(text);
            assetLogMapper.insertSelective(assetLog);
        }
    }

    // 取消日志
    private void insertLog2(String handlerId,List<String> assetIdList) {
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();
        if(assetIdList!=null){
            for (String assetId:assetIdList) {
            AssetLog assetLog = new AssetLog();
            assetLog.setCreateTime(DateTools.nowDate());
            assetLog.setCreateUser(userId);
            assetLog.setUpdateTime(DateTools.nowDate());
            assetLog.setUpdateUser(userId);
            assetLog.setLogType("资产调拨");
            assetLog.setAssetId(assetId);
            assetLog.setHandlerUser(userName);
            assetLog.setHandlerId(handlerId);
            String text = "管理员["+userName+"]取消调拨";
            assetLog.setHandlerContext(text);
            assetLogMapper.insertSelective(assetLog);
            }
        }
    }

    // 调入日志
    private void insertLog3(TransferParam transfer) {
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();

        List<TransferDetail> detailList = transfer.getDetailList();
        if(detailList!=null){
            for (TransferDetail detail:detailList) {
                AssetLog assetLog = new AssetLog();
                assetLog.setCreateTime(DateTools.nowDate());
                assetLog.setCreateUser(userId);
                assetLog.setUpdateTime(DateTools.nowDate());
                assetLog.setUpdateUser(userId);
                assetLog.setLogType("资产调拨");
                assetLog.setAssetId(detail.getAssetId());
                assetLog.setHandlerUser(userName);
                assetLog.setHandlerId(transfer.getTransferId());
                WarehouseResult warehouseResult = warehouseService.queryByAssetId(detail.getAssetId());
//                String text = "调拨确认，将资产【使用人】字段由 \""+warehouseResult.getHandlerUser()+"\" 变更为 ["+userName+"]";
                TransferResult transferResult = mapper.selectByTransferId(transfer.getTransferId());
                LogContext context  =  new LogContext();
                context.setModelName("调拨确认，");
                context.setBeforeuseCompanyName(transferResult.getTransferOutCompanyName());
                context.setAfteruseCompanyName(" "+transferResult.getTransferInCompanyName());
                if(StringUtils.isNotEmpty(warehouseResult.getHandlerUser())){
                    context.setBeforeName(warehouseResult.getHandlerUser());
                    context.setBeforeState("在用");
                }else{
                    context.setBeforeName("<空>");
                    context.setBeforeState("闲置");
                }
                if(StringUtils.isNotEmpty(detail.getUseUserId())){
                    context.setAfterName(detail.getUseUsername());
                    context.setAfterState("在用");
                }else{
                    context.setAfterName("<空>");
                    context.setAfterState("闲置");
                }
                if(StringUtils.isNotEmpty(detail.getTransferInDept())){
                    context.setBeforeuseDepartmentName(warehouseResult.getUseDeptName());
                    context.setAfteruseDepartmentName(warehouseMapper.queryOrgById(detail.getTransferInDept()).getName());
                }
                context.setBeforeArea(warehouseResult.getAreaName());
                context.setAfterArea(areaMapper.selectByPrimaryKey(detail.getTransferInArea()).getName());

                assetLog.setHandlerContext(ChangLogUtil.simpleLogContxt(context));
                assetLogMapper.insertSelective(assetLog);
            }
        }
    }
    // 打回日志
    private void insertLog4(String handlerId,List<String> assetIdList) {
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();
        if(assetIdList!=null){
            for (String assetId:assetIdList) {
                AssetLog assetLog = new AssetLog();
                assetLog.setCreateTime(DateTools.nowDate());
                assetLog.setCreateUser(userId);
                assetLog.setUpdateTime(DateTools.nowDate());
                assetLog.setUpdateUser(userId);
                assetLog.setLogType("资产调拨");
                assetLog.setAssetId(assetId);
                assetLog.setHandlerUser(userName);
                assetLog.setHandlerId(handlerId);
                TransferResult transferResult = queryTransfer(handlerId);
                String text = "管理员["+userName+"]将资产打回到["+transferResult.getTransferOutCompanyName()+"]";
                assetLog.setHandlerContext(text);
                assetLogMapper.insertSelective(assetLog);
            }
        }
    }

    /**
     * 确定调入
     * @param transfer
     */
    public Integer transferSuccess(TransferParam transfer) {
        String token = request.getHeader("token");
        String userId = request.getHeader("userId");
        String orgId = request.getHeader("orgId");
        LoginUser user = cacheUtils.getUser(token);
        List<TransferDetail> detailList = transfer.getDetailList();
        AtomicInteger i = new AtomicInteger();
        Transfer tra = mapper.selectByPrimaryKey(transfer.getTransferId());

        for (TransferDetail detail : detailList) {
            // 修改子表
            Example example = new Example(AssetTransfer.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("transferId",transfer.getTransferId());
            criteria.andEqualTo("assetId",detail.getAssetId());
            AssetTransfer at = new AssetTransfer();
            at.setState(1);
            at.setTransferInDate(detail.getTransferInDate());
            transfer.setTransferInTime(detail.getTransferInDate());
            assetTransferMapper.updateByExampleSelective(at, example);

            Warehouse warehouse = new Warehouse();

            // 调入人ID 不能为空
            if(StringUtils.isNotEmpty(detail.getUseUsername())){
                UserManagement userM = warehouseMapper.queryUserByUsername(detail.getUseUsername(),orgId,null);
                OrgManagement org = warehouseMapper.queryOrgById(userM.getCompanyId());
                OrgManagement dept = warehouseMapper.queryOrgById(userM.getDeptId());
                tra.setTransferInCompany(org.getId());
                tra.setTransferInCompanyTreecode(org.getTreecode());
                detail.setTransferInDept(dept.getId());
                detail.setTransferInDeptTreecode(dept.getTreecode());
                warehouse.setState("在用");
            }else{
                detail.setUseUserId("");
                detail.setUseUsername("");
                warehouse.setState("闲置");
            }
            warehouse.setAssetId(detail.getAssetId());
            warehouse.setHandlerUser(detail.getUseUsername());
            warehouse.setHandlerUserId(detail.getUseUserId());

            warehouse.setCompany(tra.getTransferInCompany());
            warehouse.setCompanyTreecode(tra.getTransferInCompanyTreecode());
            warehouse.setUseCompany(tra.getTransferInCompany());
            warehouse.setUseCompanyTreecode(tra.getTransferInCompanyTreecode());

            warehouse.setUseDepartment(detail.getTransferInDept());
            warehouse.setUseDeptTreecode(detail.getTransferInDeptTreecode());

            warehouse.setAdmin(user.getUserName());
            warehouse.setArea(detail.getTransferInArea());
            if(StringUtils.isNotEmpty(detail.getTransferInAddress())){
                warehouse.setStorageLocation(detail.getTransferInAddress());
            }
            warehouse.setAdminId(user.getUserId());
            warehouseMapper.updateByPrimaryKeySelective(warehouse);

            Example example2  = new Example(WarehouseHistory.class);
            Example.Criteria criteria1 = example2.createCriteria();
            criteria1.andEqualTo("handerId",transfer.getTransferId());
            criteria1.andEqualTo("assetId",warehouse.getAssetId());
            criteria1.andEqualTo("handerType",4);
            WarehouseHistory wh = new WarehouseHistory();
            BeanUtils.copyProperties(warehouse,wh);
            historyMapper.updateByExampleSelective(wh,example2);
            i.getAndIncrement();

           if(StringUtils.isNotEmpty(warehouse.getHandlerUserId())){
               AssetReport assetReport = new AssetReport();
               assetReport.setAssetId(warehouse.getAssetId());
               assetReport.setAmount(warehouse.getAmount());
               assetReport.setArYear(DateTools.currentYear());
               assetReport.setArMonth(DateTools.currentMonth());
               assetReport.setArDay(DateTools.currentDay());
               assetReport.setUseType(0);
               assetReport.setUseUserId(warehouse.getHandlerUserId());
               assetReportService.insertReport(assetReport);
           }
        }
        transferComplete(transfer);
        // 日志
        insertLog3(transfer);

        //推送消息给领用人
        String[] asia = {tra.getTransferOutAdmin()};
        String notification_title = "资产调拨确认";
        String msg_title = "资产调拨确认";
        String msg_content = "资产调拨确认，单号【"+ tra.getTransferOrderNo() +"】";
        log.info("资产调拨确认,消息推送人："+ JSONObject.toJSONString(asia));
        JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");
        String finalMsg_content = msg_content;
        Arrays.stream(asia).forEach(e->{
            PushManagement pu = new PushManagement();
            pu.setCompanyId(orgId);
            pu.setContent(finalMsg_content);
            pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            pu.setCuser(userId);
            pu.setSender(e);
            pu.setResult(0);
            pushMapper.insertSelective(pu);
        });

        return i.get();
    }

    /**
     * 打回调入
     * @param transfer
     */
    public Integer transferBack(TransferParam transfer) {
        String userId = request.getHeader("userId");
        String orgId = request.getHeader("orgId");
        List<String> assetIdList = transfer.getDetailList().stream()
                .map(e->e.getAssetId()).collect(Collectors.toList());

        Example example = new Example(AssetTransfer.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("transferId",transfer.getTransferId());
        criteria.andIn("assetId",assetIdList);
        AssetTransfer at = new AssetTransfer();
        at.setState(3);
        int i = assetTransferMapper.updateByExampleSelective(at, example);

        TransferResult transferResult = mapper.selectByTransferId(transfer.getTransferId());
        for(String assetId:assetIdList){
            Warehouse warehouse = warehouseMapper.selectByPrimaryKey(assetId);
            ArrayList<String> arrayList = new ArrayList<>();
            arrayList.add(assetId);
            if(StringUtils.isNotEmpty(warehouse.getHandlerUser())){
                warehouseService.updateAssetState(arrayList, "在用",null,null);

            }else{
                warehouseService.updateAssetState(arrayList, "闲置",null,null);
            }

        }
        transferComplete(transfer);

        //推送消息给领用人
        String[] asia = {transferResult.getTransferOutAdmin()};
        String notification_title = "资产调拨打回";
        String msg_title = "资产调拨打回";
        String msg_content = "资产调拨打回，单号【"+ transferResult.getTransferOrderNo() +"】";
        log.info("资产调拨打回,消息推送人："+ JSONObject.toJSONString(asia));
        JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");
        String finalMsg_content = msg_content;
        Arrays.stream(asia).forEach(e->{
            PushManagement pu = new PushManagement();
            pu.setCompanyId(orgId);
            pu.setContent(finalMsg_content);
            pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            pu.setCuser(userId);
            pu.setSender(e);
            pu.setResult(0);
            pushMapper.insertSelective(pu);
        });

        // 打回日志
        insertLog2(transfer.getTransferId(),assetIdList);
        return i;
    }

    /**
     * 主表已完成
     * @param transfer
     */
    private void transferComplete(TransferParam transfer) {
        String token = request.getHeader("token");
        String userId = cacheUtils.getUser(token).getUserId();
        transfer.setCreateUser(userId);
        transfer.setUpdateTime(DateTools.nowDate());
        Example example = new Example(AssetTransfer.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("transferId",transfer.getTransferId());
        List<AssetTransfer> assetTransfers = assetTransferMapper.selectByExample(example);
        List<Integer> stateList = assetTransfers.stream()
                .filter(e->e.getState()==0)
                .map(e -> e.getState())
                .collect(Collectors.toList());
        if(stateList==null || stateList.size()==0){
            // 修改已完成
            transfer.setTransferState("1");
            mapper.updateByPrimaryKeySelective(transfer);
        }else{
            mapper.updateByPrimaryKeySelective(transfer);
        }
    }

    /**
     * 取消调入
     * @param transferId
     * @return
     */
    public Integer updateCancel(String transferId) {
        //-----修改子表
        Example example = new Example(AssetTransfer.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("transferId",transferId);
        AssetTransfer at= new AssetTransfer();
        at.setState(2);
        assetTransferMapper.updateByExampleSelective(at,example);
        List<AssetTransfer> assetTransferList = assetTransferMapper.selectByExample(example);
        //-----修改主表
        Transfer transfer = new Transfer();
        transfer.setTransferId(transferId);
        transfer.setTransferState("2");
//        transfer.setTransferInTime(DateTools.nowDay());
        int i = mapper.updateByPrimaryKeySelective(transfer);
        Example example1 = new Example(AssetTransfer.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("transferId",transferId);
        criteria1.andEqualTo("reserved","1");
        List<AssetTransfer> assetTransfers1 = assetTransferMapper.selectByExample(example1);
        List<String> assetIdList = assetTransfers1.stream().map(e -> e.getAssetId()).collect(Collectors.toList());
        warehouseService.updateAssetState(assetIdList, "闲置",null,null);

        Example example2 = new Example(AssetTransfer.class);
        Example.Criteria criteria2 = example2.createCriteria();
        criteria2.andEqualTo("transferId",transferId);
        criteria2.andEqualTo("reserved","2");
        List<AssetTransfer> assetTransfers2 = assetTransferMapper.selectByExample(example2);
        List<String> assetIdList2 = assetTransfers2.stream().map(e -> e.getAssetId()).collect(Collectors.toList());
        warehouseService.updateAssetState(assetIdList2, "在用",null,null);
        List<String> assetIdList3 = assetTransferList.stream().map(AssetTransfer::getAssetId).collect(Collectors.toList());
        // 取消日志
        insertLog2(transfer.getTransferId(),assetIdList3);
        return i;
    }

    public Workbook printTransfer(List<String> transferIdList){
        HSSFWorkbook wb=new HSSFWorkbook();
        String title = "资产调拨单";
        for (String transferId:transferIdList) {
//       数据
            TransferResult transferResult = queryTransfer(transferId);
            String sheetName=transferResult.getTransferOrderNo();
            HSSFSheet sheet=wb.createSheet(sheetName);
            // 设置打印页面
            ExcelStyle.printSetup(sheet);
            sheet.setDefaultColumnWidth(12);
            sheet.setColumnWidth(0,5*256);

            HSSFRow row_title = sheet.createRow(0);
            row_title.setHeight((short) (38 * 20));
            HSSFCell cell_title = row_title.createCell(1);
            cell_title.setCellValue(title);
            cell_title.setCellStyle(ExcelStyle.styleTitle(wb));
            row_title.setHeight((short)690);
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 8)); // 合并单元格显示
            String[] cellName={ "调拨单号：","调拨日期：","调拨人：",
                    "调出使用公司：","调入使用公司：","调入区域：",
                    "调入存放地点：","调拨备注："};
            String[] cellValue={ transferResult.getTransferOrderNo(),transferResult.getTransferOutTime(),transferResult.getTransferInAdminName(),
                    transferResult.getTransferOutCompanyName(),transferResult.getTransferInCompanyName(),transferResult.getTransferInAreaName(),
                    transferResult.getTransferInAddress(),transferResult.getTransferRemark()};
            AtomicInteger cellCount = new AtomicInteger();
            AtomicInteger valCount = new AtomicInteger();
            for (int i = 1; i < 3 ; i++) {
                HSSFRow row = sheet.createRow(i);
                for(int c = 1 ;c< 9; c++){
                    HSSFCell cell = row.createCell(c);
                    if(c%3==1){
                        cell.setCellValue(cellName[cellCount.getAndIncrement()]);
                        cell.setCellStyle(ExcelStyle.styleNotBorder(wb,0));
                        continue;
                    }
                    if(c%3==0 || (i==3 && c>2 )||(i==4 && c>2)){
                        cell.setCellValue("");
                        cell.setCellStyle(ExcelStyle.styleNotBorder(wb,0));
                        continue;
                    }
                    cell.setCellValue(cellValue[valCount.getAndIncrement()]);
                    cell.setCellStyle(ExcelStyle.styleNotBorder(wb,0));
                }
            }
            CellRangeAddress cell1 = new CellRangeAddress(1, 1, 2, 3);
            CellRangeAddress cell2 = new CellRangeAddress(2, 2, 2, 3);// 合并单元格显示
            CellRangeAddress cell3 = new CellRangeAddress(3, 3, 2, 8);// 合并单元格显示
            CellRangeAddress cell4 = new CellRangeAddress(4, 4, 2, 8);// 合并单元格显示
            sheet.addMergedRegion(cell1);
            sheet.addMergedRegion(cell2);
            sheet.addMergedRegion(cell3);
            sheet.addMergedRegion(cell4);

            Row row = sheet.createRow(5);
            row.setHeight((short)600);
            Cell cell = row.createCell(1);
            cell.setCellValue("资产明细：");
            cell.setCellStyle(ExcelStyle.styleNotBorder(wb,1));

            String[] colName={"序号","资产条码","资产类别","资产名称",
                    "规格型号","SN号","金额","管理员"};
            row = sheet.createRow(6);
            AtomicInteger colNum = new AtomicInteger();
            for (int i = 1; i <9; i++) {
                cell = row.createCell(i);
                cell.setCellValue(colName[colNum.getAndIncrement()]);
                cell.setCellStyle(ExcelStyle.styleCellName(wb));
            }
            List<WarehouseHistoryResult> warehouseList = transferResult.getWarehouseList();
            AtomicInteger rowNum = new AtomicInteger(7);
            AtomicInteger numNo = new AtomicInteger(1);
            if(warehouseList!=null) {
                for (int i = 0; i < warehouseList.size(); i++) {
                    WarehouseHistoryResult warehouseResult = warehouseList.get(i);
                    String[] colValue = {warehouseResult.getAssetCode(), warehouseResult.getAssetClassName(),
                            warehouseResult.getAssetName(), warehouseResult.getSpecificationModel(),
                            warehouseResult.getSnNumber(), warehouseResult.getAmount(), warehouseResult.getAdmin()};
                    row = sheet.createRow(rowNum.getAndIncrement());
                    // 序号
                    cell = row.createCell(1);
                    cell.setCellValue(i + 1);
                    cell.setCellStyle(ExcelStyle.styleCellValue(wb));
                    // 数据
                    AtomicInteger cellNum = new AtomicInteger(0);
                    for (int j = 2; j < 9; j++) {
                        cell = row.createCell(j);
                        String str = colValue[cellNum.getAndIncrement()];
                        cell.setCellValue(str);
                        cell.setCellStyle(ExcelStyle.styleCellValue(wb));
                    }
                }
            }
            // 页尾
            row = sheet.createRow(rowNum.getAndIncrement());
            cell = row.createCell(1);
            cell.setCellValue("调拨人签字：");
            cell.setCellStyle(ExcelStyle.styleNotBorder(wb,0));

            cell = row.createCell(7);
            cell.setCellValue("签字时间：");
            cell.setCellStyle(ExcelStyle.styleNotBorder(wb,0));
        }
        return wb;
    }

    public boolean checkTransfer(String transferId) {
        Example example = new Example(AssetTransfer.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("transferId",transferId);
        List<AssetTransfer> assetTransfers = assetTransferMapper.selectByExample(example);
        for(AssetTransfer at :assetTransfers){
            if(at.getState()!=0){
                return true;
            }
        }
        return false;
    }

    public List<UserManagement> transferInAdmin(String companyId) {

        List<UserManagement> list = mapper.transferInAdmin(companyId);
        return list;
    }
}
